#pragma once

#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/wait.h>
#include <pthread.h>
#include <functional>

#include "Log.hpp"
#include "Com_ERR.hpp"
#include "Inet_Addr.hpp"

const static int g_sockfd = -1;
const static int g_backlog = 8; // 连接队列的大小

using namespace LogModule;

using service_t = std::function<void(int, Inet_Addr)>;// 包装一个可调用的函数对象类型

class TcpServer
{
private:
    static void *Execute(void *args)
    {
        pthread_detach(pthread_self()); // 将自己给分离了，避免主线程等待，以及出现类似于僵尸的问题
        ThreadData *td = static_cast<ThreadData *>(args);
        td->_self->_service(td->_sockfd, td->_addr);// 线程回调任务函数
        ::close(td->_sockfd);
        delete td;
        return nullptr;
    }

public:
    TcpServer(uint16_t port, service_t service)
        : _listensocket(g_sockfd), _port(port), _isrunning(false),_service(service)
    {
    }

    void InitServer()
    {
        // 1、创建监听套接字
        _listensocket = ::socket(AF_INET, SOCK_STREAM, 0);
        if (_listensocket < 0)
        {
            LOG(FATAL, "socket create error\n");
            exit(SOCKET_ERROR);
        }
        LOG(INFO, "socket create success, sockfd is %d\n", _listensocket);

        // 2、绑定主机的信息
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;         // IPV4
        local.sin_port = htons(_port);      // 设置端口
        local.sin_addr.s_addr = INADDR_ANY; // 任意 ip
        if (::bind(_listensocket, (struct sockaddr *)&local, sizeof(local)))
        {
            LOG(FATAL, "bind error\n");
            exit(BIND_ERROR);
        }
        LOG(INFO, "bind success\n");
        // 3、设置监听
        int n = ::listen(_listensocket, g_backlog);
        if (n < 0)
        {
            LOG(FATAL, "listen error");
            exit(LISTEN_ERROR);
        }
        LOG(INFO, "listen success");
    }

    // 内部类
    class ThreadData
    {
    public:
        ThreadData(int sockfd, Inet_Addr &addr, TcpServer *self)
            : _sockfd(sockfd), _addr(addr), _self(self)
        {
        }

    public:
        int _sockfd;
        Inet_Addr _addr;
        TcpServer *_self;
    };

    void Start()
    {
        _isrunning = true;
        while (_isrunning)
        {
            // 4、获取链接
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = ::accept(_listensocket, (struct sockaddr *)&peer, &len);
            if (sockfd < 0)
            {
                LOG(WARNING, "accept error\n");
            }
            LOG(INFO, "accept success\n");
            // 处理业务
            Inet_Addr addr(peer);
            // version 2 多线程版
            pthread_t tid;
            ThreadData *td = new ThreadData(sockfd, addr, this);
            pthread_create(&tid, nullptr, Execute, td);
        }
        _isrunning = false;
    }

    ~TcpServer()
    {
        if (_listensocket > g_sockfd)
        {
            ::close(_listensocket);
        }
    }

private:
    int _listensocket;  // 监听套接字
    uint16_t _port;     // 端口号
    bool _isrunning;    // 服务端状态
    service_t _service; // 业务回调函数
};